package ch.bfh.medinfo.speakingsms.receiver.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

//http://www.apriorit.com/our-company/dev-blog/227-handle-sms-on-android
public class SMSInReceiver extends BroadcastReceiver {
	public static final String SMS_EXTRA_NAME = "pdus";
	public static final String KEYWORD = "SPEAK:";

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent == null) {
			return;
		}
		// Get the SMS map from Intent
		Bundle extras = intent.getExtras();

		if (extras != null) {
			// Get received SMS array
			Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);

			// Get ContentResolver object for pushing SMS to the
			// incoming folder
			// ContentResolver contentResolver = context.getContentResolver();

			for (int i = 0; i < smsExtra.length; ++i) {
				SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
				String body = sms.getMessageBody().toString();
				String address = sms.getOriginatingAddress();
				
				Intent speakingSMSServiceIntent=SpeakingSMSService.getSpeakingSMSIntent(address, body);
				if(speakingSMSServiceIntent!=null)
				{
					context.startService(speakingSMSServiceIntent);
					// WARNING!!!
					// If you uncomment the next line then received SMS will
					// not be put to incoming.
					// Be careful!
					// this.abortBroadcast();
				}
			}

		}

	}

}
